package com.ciaojian.client.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.ciaojian.client.util.RedisKey;
import com.ciaojian.client.util.TimeInterval;
import com.ciaojian.core.enums.business.ShareRecordPlatformEnum;
import com.ciaojian.core.enums.business.CouponCodeOriginEnum;
import com.ciaojian.core.enums.sys.SysSettingEnum;
import com.ciaojian.core.factory.ObjectMapperFactory;
import com.ciaojian.core.mapper.UserMapper;
import com.ciaojian.core.model.ShareRecord;
import com.ciaojian.core.model.User;
import com.ciaojian.core.service.UserService;
import com.ciaojian.client.util.Conver;
import com.ciaojian.core.util.LogUtil;
import com.ciaojian.client.util.StringTool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author Atlakyn
 */
@Service
public class UserServiceImpl extends UserService<UserMapper, User> implements IService<User> {
//
//    @Resource
//    private RedisTemplate<String, TokenUser> tokenRedisTemplate;
    @Resource
    private CouponCodeServiceImpl couponCodeService;
    @Resource
    private SettingServiceImpl settingService;
    @Resource
    private ShareRecordServiceImpl shareRecordService;
    @Resource
    private CouponServiceImpl couponService;

    @Override
    public String getOpenIdById(Integer id) {
        return baseMapper.getOpenIdById(id);
    }

    /**
     * 邀请注册成功
     *
     * @param invitedId 分享人Id
     * @param userId    被邀请人
     */
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void invited(Integer invitedId, Integer userId) {
        // 如果不是分享过来注册的直接退出
        if (invitedId == null) {
            return;
        }

        ShareRecord shareRecord = new ShareRecord();
        shareRecord.setInviteId(invitedId);
        shareRecord.setShareId(userId);
        shareRecord.setPlatform(ShareRecordPlatformEnum.wechat);
        LogUtil.writeBusinessLog(String.format("注册成功,分享人:{%s},被分享人:{%s},分享记录:{%s}", shareRecord.getInviteId(), userId, shareRecord.getId()));
        // 给新用户发券
        String settingValue = settingService.getBaseMapper().getValue(SysSettingEnum.SHARE_SETTING.getName());
        ObjectMapper om = ObjectMapperFactory.getObjectMapperInstance();
        try {
            // 分享设置转为 JsonNode
            JsonNode jsonNode = om.readTree(settingValue);
            // 新人奖励的优惠券id
            int invitedCouponId = jsonNode.get("invited").asInt();
            couponCodeService.getBaseMapper().updateByCouponId(userId,
                    invitedCouponId,
                    CouponCodeOriginEnum.invited_register_reward,
                    couponService.getCouponExpiredTime(invitedCouponId));

            // 给分享人发券
            // 分享成功的次数
            int count = shareRecordService.getBaseMapper().countByInvited(shareRecord.getInviteId()) + 1;

            // 分享设置转为 JsonNode
            for (JsonNode share : jsonNode.get("share")) {
                int countSetting = share.get("count").asInt();
                if (countSetting == count) {
                    int sharedCoupon = share.get("sharedCoupon").asInt();
                    couponCodeService.getBaseMapper().updateByCouponId(shareRecord.getInviteId(),
                            sharedCoupon,
                            CouponCodeOriginEnum.share_reward,
                            couponService.getCouponExpiredTime(invitedCouponId));
                    break;
                }
            }
            shareRecord.insert();
        } catch (JsonProcessingException e) {
            LogUtil.writeErrorLog(String.format("method invited(Integer,Integer) 抛出异常,异常信息: {%s}", e.getMessage()));
            LogUtil.writeErrorLog(String.format("settingValue 的值是:{%s}", settingValue));
            e.printStackTrace();
        }
    }

//    /**
//     * 判断用户的token是否有效
//     *
//     * @param userId
//     * @param tokenId
//     * @param storeChief
//     * @return
//     */
//    public boolean isUserTokenValid(String userId, String tokenId) {
//        String loginKey = RedisKey.getTokenExpireKey(userId);
//        String expireTime = (String) tokenRedisTemplate.opsForHash().get(loginKey, tokenId);
//        if (StringTool.isEmpty(expireTime)) {
//            return false;
//        }
//        // 过期的时间小于当前时间，表示已经过期
//        if (Conver.toLong(expireTime, 0L) < System.currentTimeMillis()) {
//            tokenRedisTemplate.opsForHash().delete(loginKey, tokenId);
//            return false;
//        }
//        return true;
//    }

    /**
     * 判断用户的有效期过期时间是否大于7天
     *
     * @return
     */
    public boolean checkEndTime(String storeId, Long endTime) {

//        if (endTime == null || endTime == 0) {
//            SaasStoreInfoCache saasStoreInfoCache = saasStoreCacheService.saasStoreInfo(Long.parseLong(storeId));
//
//            if (saasStoreInfoCache == null || saasStoreInfoCache.getEndTime() == 0) {
//                return false;
//            }
//            endTime = saasStoreInfoCache.getEndTime() + 7 * 24 * 60 * 60 * 1000L;
//            if (endTime < System.currentTimeMillis()) {
//                return false;
//            }
//            return true;
//        }
        endTime = endTime + 7 * 24 * 60 * 60 * 1000L;
        if (endTime < System.currentTimeMillis()) {
            return false;
        }
        return true;
    }

//    /**
//     * 刷新用户的token信息
//     *
//     * @param userId  用户id
//     * @param tokenId token信息
//     */
//    public void refreshUserTokenInfo(String userId, String tokenId) {
//        addTokenExpireToRedis(userId, tokenId,120);
//    }

//    /**
//     * 储存token
//     *
//     * @param userId
//     * @param tokenId
//     */
//    private void addTokenExpireToRedis(String userId, String tokenId,int sminute) {
//        String loginKey = RedisKey.getTokenExpireKey(userId);
//        // 2小时(毫秒)后过期, 小时内操作会续航
//        long expireTime = System.currentTimeMillis() + TimeInterval.MILLISECOND_PER_MINUTE * sminute;
//        //log.info("userIdKey:{},tokenId:{}", loginKey, tokenId);
//        tokenRedisTemplate.opsForHash().put(loginKey, tokenId, String.valueOf(expireTime));
//        //log.info("expireTime:{}", tokenRedisTemplate.opsForHash().get(loginKey, tokenId));
//    }

}